/*
 * Copyright 2009-2010 Nobject.org, All Rights Reserved.
 * 
 * This software is licensed under LGPL license.
 * See terms of license at gnu.org.
 * 
 * For more information,visit:
 * 
 * http://www.nobject.org
 */
package org.nobject.common.apps;

/**
 * 身份证工具类
 * 
 * @author bianrongjun
 * @version 1.0
 */
public class IDCardUtils {

	/**
	 * 15位身份证号转换为18位
	 * @param oldID 15位身份证
	 */
	public static String from15to18(String oldID) {
		java.util.regex.Pattern pat = java.util.regex.Pattern.compile("[0-9]*");
		String result = ""; // 转换后的身份证
		int last = 0; // 最后一位
		if (oldID != null && oldID.length() == 15 && (pat.matcher(oldID).matches())) {
			result = oldID.substring(0, 6) + "19" + oldID.substring(6, 15);// 转换为17位
			for (int i = 16; i >= 0; i--)
				last += (Math.pow(2, i + 1) % 11) * (Integer.parseInt(result.substring(16 - i, 16 - i + 1)));
			if ((last = last % 11) == 0) { // 添加最后一位
				return result += "1";
			} else if ((last = last % 11) == 1) {
				result += "0";
			} else if ((last = last % 11) == 2) {
				result += "x";
			} else {
				result += (12 - (last = last % 11));
			}
		} else if (oldID.length() == 18) {
			return oldID;
		} else {
			return null;
		}
		return result;
	}

	/**
	 * 18位身份证号转换为15位
	 * @param newID
	 */
	public static String from18to15(String newID) {
		String result = "";
		if (newID != null && newID.length() == 18) {
			result = newID.substring(0, 6) + newID.substring(8, 17);
			return result;
		}
		return null;
	}
}
